package com.david.IfaceAutoTest.controller;

import com.david.IfaceAutoTest.entity.Project;
import com.david.IfaceAutoTest.service.ProjectService;
import io.swagger.annotations.*;

import java.io.IOException;

import com.david.IfaceAutoTest.entity.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 控制层
 *
 * @author david
 * @since 2021-12-14
 */
@RestController
@Api(tags = "project接口")
@RequestMapping("/IfaceAutoTest/project")
public class ProjectController {

    private final ProjectService projectservice;

    @Autowired
    public ProjectController(ProjectService projectservice) {
        this.projectservice = projectservice;
    }

    @GetMapping("/list")
    @ApiOperation(value = "列表查询", notes = "list")
    public CommonResult<Object> list() {
        return CommonResult.success(projectservice.list());
    }

    @GetMapping("/get")
    @ApiOperation(value = "详情查询", notes = "get")
    public CommonResult<Object> get(Integer id) {
        return CommonResult.success(projectservice.getById(id));
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存", notes = "save")
    public CommonResult<Object> save(Project project) {
        return CommonResult.success(projectservice.save(project));
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除", notes = "delete")
    public CommonResult<Object> delete(Integer id) {
        projectservice.removeById(id);
        return CommonResult.success();
    }

    @ApiOperation("级联删除项目、删除项目下所有子项")
    @DeleteMapping(value = "cascade_del")
    public CommonResult<Object> cascadeDelProject(Integer projectId) {
        projectservice.cascadeDelProject(projectId);
        return CommonResult.success();
    }

    @ApiOperation("接口文件上传")
    @PostMapping("/upload")
    public CommonResult<Object> upload(@RequestParam MultipartFile multipartFile) throws IOException {
        //校验文件格式
        boolean validateFileResult;
        try {
            validateFileResult = projectservice.validateFile(multipartFile);
        } catch (IOException e) {
            return CommonResult.failed(e.getMessage());
        }

        if (validateFileResult) {
            projectservice.upload(multipartFile);
            //解析入库
            return CommonResult.success();

        } else {
            return CommonResult.validateFailed("不符合上传文件格式要求");
        }

    }
}
